import { Router } from 'express';
import { IResp } from '../../types';
import superagent from 'superagent';
import LRU from 'lru-cache';

const router = Router();

function walmartTypeahead (pq) {
  return new Promise((resolve) => {
    const baseUrl = 'https://www.walmart.com/typeahead/v3/complete';
    const ec = encodeURIComponent;
    const data : Array<Array<any>> = [];
    const arr = [''];
    let i;
    for (i = 97; i < 122; i++) {
      arr.push(String.fromCharCode(i));
    }
    for (i = 0; i < 10; i++) {
      arr.push(i + '');
    }

    (function Iteration () {
      if (arr.length === 0) {
        resolve(data);
        return;
      }
      const w = arr.shift();
      console.log(`get '${pq} ${w}' ...`);
      request(w).then(res => {
        const list = parseRes(res);
        if (list.length > 0) {
          list.unshift(w);
          data.push(list);
        }
        Iteration();
      }, () => {
        // const list : Array<any> = [w, '#加载失败#'];
        // data.push(list);
        Iteration();
      });
    })();

    function parseRes (res) {
      return res._body.queries.map(v => v.displayName + (!v.metaData || v.metaData.deptId === '0' ? '' : ` (${v.metaData.deptName || ''})`));
    }

    function request (w) {
      return superagent
        .get(baseUrl + '?term=' + (w ? ec(pq + ' ' + w) + '&pq=' + ec(pq) : ec(pq)))
        .set({
          'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36'
        });
    }
  });
}

const walmartCache = new LRU({
  ttl: 60 * 60 * 1000,
  max: 10
});

// 判断账户是否存在（是否已初始化）
router.get('/walmartTypeahead', async (req, res) => {
  let resp: IResp;
  try {
    const { word, fresh } = req.query;
    if (!word) {
      resp = {
        code: -1
      };
    } else {
      let data;
      if (!fresh && walmartCache.has(word)) {
        data = walmartCache.get(word);
      } else {
        data = await walmartTypeahead(word);
        walmartCache.set(word, data);
      }
      resp = {
        code: 1,
        data
      };
    }
  } catch (err) {
    console.error(err);
    resp = {
      code: -1
    };
  }
  res.json(resp);
});

export default router;
